﻿@using System.Web.Script.Serialization
@{
    ViewBag.Title = "Create";
    Layout = "~/views/shared/_Layout.cshtml";
}

<h2>Create</h2>


<label>UserName</label>
<input type="text" data-bind="value:UserName"/>

<label>Email</label>
<input type="text" data-bind="value:Email"/>

<label>password</label>
<input type="password" data-bind="value:Password"/>


<label>roles</label>
 <!-- ko foreach: Roles -->
    <input type="checkbox" data-bind="value:Id, checked: $root.SelectedRoles" /><span data-bind="text:Name"></span>
<!-- /ko -->

<input type="button" value="login" data-bind="click:SaveCustomer"/>



@{
    var model = ViewBag.Model;

    var jsonStr = new HtmlString(new JavaScriptSerializer().Serialize(model));
}
@section scripts{
    <script>
        var init = @jsonStr;
        function CustomerRoleModel(id, name) {
            var self = this;
            self.Id = ko.observable(id);
            self.Name= ko.observable(name);
        }

        function CustomerEditModel() {
            var self = this;
            self.UserName = ko.observable(init.UserName);
            self.Password= ko.observable(init.Password);
            self.Email= ko.observable(init.Email);

            var tempRoles = $.isEmptyObject(init.AvailableRoles)? []: $.map(init.AvailableRoles, function (a) {
                return new CustomerRoleModel(a.Id, a.Name);
            });

            self.Roles = ko.observableArray(tempRoles);
            self.SelectedRoles = ko.observableArray();
            
            self.SaveCustomer = function() {
                $.ajax({
                    url: "/api/CustomerAdminApi/SaveCustomer",
                    type: 'post',
                    data: ko.toJSON(self),
                    contentType: 'application/json',
                    success: function(result) {

                        if (result.Status == "0") {
                            alert("登录成功");
                            //location.href = '' + result.Id;
                        } else {
                            alert("登录失败：" + result.Message);
                        }
                    }
                });
            };
        }

        var vm = new CustomerEditModel();
        ko.applyBindings(vm);
        
    </script>

}